package com.coai.ai.controller

import com.coai.ai.service.*
import kotlinx.coroutines.runBlocking
import org.springframework.web.bind.annotation.*

@RestController
@RequestMapping("/api/ai")
class AIController(
    private val customerServiceEngine: CustomerServiceEngine,
    private val meetingAnalysisEngine: MeetingAnalysisEngine,
    private val salesAssistantEngine: SalesAssistantEngine,
    private val openAIService: OpenAIService
) {
    
    /**
     * 智能客服
     */
    @PostMapping("/customer-service")
    fun customerService(@RequestBody request: CustomerServiceRequest): CustomerServiceResponse = runBlocking {
        customerServiceEngine.handleCustomerQuery(
            customerId = request.customerId,
            query = request.query,
            conversationId = request.conversationId,
            context = request.context
        )
    }
    
    /**
     * 会议分析
     */
    @PostMapping("/meeting-analysis")
    fun analyzeMeeting(@RequestBody request: MeetingAnalysisRequest): MeetingAnalysisResult = runBlocking {
        meetingAnalysisEngine.analyzeMeeting(
            transcript = request.transcript,
            participants = request.participants
        )
    }
    
    /**
     * 提取任务
     */
    @PostMapping("/extract-tasks")
    fun extractTasks(@RequestBody request: ExtractTasksRequest): List<ActionItem> = runBlocking {
        val result = meetingAnalysisEngine.analyzeMeeting(request.content, emptyList())
        result.actionItems
    }
    
    /**
     * 销售话术
     */
    @PostMapping("/sales-script")
    fun generateSalesScript(@RequestBody request: SalesScriptRequest): SalesScriptResponse = runBlocking {
        salesAssistantEngine.generateSalesScript(
            customerId = request.customerId,
            stage = request.stage,
            context = request.context
        )
    }
    
    /**
     * 内容生成
     */
    @PostMapping("/generate-content")
    fun generateContent(@RequestBody request: ContentGenerationRequest): ContentGenerationResponse = runBlocking {
        val prompt = buildContentPrompt(request.contentType, request.params)
        val content = openAIService.chatCompletion(
            listOf(com.theokanning.openai.completion.chat.ChatMessage("user", prompt))
        )
        
        ContentGenerationResponse(
            content = content,
            suggestions = emptyList(),
            keywords = emptyList()
        )
    }
    
    /**
     * 情绪分析
     */
    @PostMapping("/sentiment-analysis")
    fun analyzeSentiment(@RequestBody request: SentimentAnalysisRequest): SentimentResult = runBlocking {
        openAIService.analyzeSentiment(request.text)
    }
    
    /**
     * 语义搜索
     */
    @PostMapping("/semantic-search")
    fun semanticSearch(@RequestBody request: SemanticSearchRequest): SemanticSearchResponse = runBlocking {
        // 实现向量搜索
        try {
            // TODO: 实际应该使用向量数据库（如 Pinecone, Milvus）
            // 1. 将查询转换为嵌入向量
            // val queryEmbedding = openAIService.createEmbedding(request.query)
            
            // 2. 在向量数据库中搜索相似消息
            // val similarMessages = vectorDB.search(queryEmbedding, limit = 10)
            
            // 3. 模拟返回相关消息ID
            val messageIds = listOf(
                "msg-${request.conversationId}-001",
                "msg-${request.conversationId}-002",
                "msg-${request.conversationId}-003"
            )
            
            logger.info("Semantic search for '${request.query}' returned ${messageIds.size} results")
            SemanticSearchResponse(messageIds = messageIds)
        } catch (e: Exception) {
            logger.error("Semantic search failed", e)
            SemanticSearchResponse(messageIds = emptyList())
        }
    }
    
    /**
     * 翻译
     */
    @PostMapping("/translate")
    fun translate(@RequestBody request: TranslateRequest): TranslateResponse = runBlocking {
        val prompt = "请将以下文本翻译成${request.targetLanguage}：\n\n${request.text}"
        val translated = openAIService.chatCompletion(
            listOf(com.theokanning.openai.completion.chat.ChatMessage("user", prompt)),
            temperature = 0.3
        )
        
        TranslateResponse(translatedText = translated)
    }
    
    private fun buildContentPrompt(contentType: String, params: Map<String, Any>): String {
        return when (contentType) {
            "PRODUCT_COPY" -> """
                请生成吸引人的商品文案：
                
                商品信息：
                ${params.entries.joinToString("\n") { "- ${it.key}: ${it.value}" }}
                
                要求：
                1. 突出卖点
                2. 吸引目标客户
                3. 包含行动号召
            """.trimIndent()
            
            "MARKETING_COPY" -> """
                请生成营销推广文案：
                
                ${params.entries.joinToString("\n") { "- ${it.key}: ${it.value}" }}
                
                要求：
                1. 有创意
                2. 引发共鸣
                3. 促进转化
            """.trimIndent()
            
            else -> "请生成内容：${params["keywords"]}"
        }
    }
}

// 请求/响应DTOs
data class CustomerServiceRequest(
    val customerId: String,
    val query: String,
    val conversationId: String,
    val context: Map<String, Any>? = null
)

data class MeetingAnalysisRequest(
    val transcript: String,
    val participants: List<String>
)

data class ExtractTasksRequest(
    val content: String
)

data class SalesScriptRequest(
    val customerId: String,
    val stage: SalesStage,
    val context: SalesContext
)

data class ContentGenerationRequest(
    val contentType: String,
    val params: Map<String, Any>
)

data class ContentGenerationResponse(
    val content: String,
    val suggestions: List<String>,
    val keywords: List<String>
)

data class SentimentAnalysisRequest(
    val text: String,
    val context: Map<String, Any>? = null
)

data class SemanticSearchRequest(
    val query: String,
    val conversationId: String
)

data class SemanticSearchResponse(
    val messageIds: List<String>
)

data class TranslateRequest(
    val text: String,
    val targetLanguage: String
)

data class TranslateResponse(
    val translatedText: String
)
